<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chinese Name Generator</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <style>
      :root {
        --chinese-red: #c8102e;
        --chinese-red-light: #ff1f3d;
      }
      body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
        background-color: #f5f5f7;
      }
      .container {
        max-width: 1000px;
      }
      .main-title {
        font-size: 2.5rem;
        font-weight: 600;
        background: linear-gradient(135deg, var(--chinese-red) 0%, var(--chinese-red-light) 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 1.5rem;
      }
      .subtitle {
        color: #86868b;
        font-size: 1.25rem;
        margin-bottom: 3rem;
      }
      .settings-btn {
        position: fixed;
        top: 20px;
        right: 20px;
        background: rgba(255, 255, 255, 0.8);
        border: 1.5px solid rgba(134, 134, 139, 0.2);
        cursor: pointer;
        padding: 12px;
        border-radius: 50%;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        backdrop-filter: blur(8px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
      .settings-btn:hover {
        background: rgba(255, 255, 255, 0.95);
        transform: scale(1.05);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
      .settings-btn svg {
        width: 28px;
        height: 28px;
        color: #1d1d1f;
        transition: all 0.3s ease;
      }
      .settings-btn:hover svg {
        color: var(--chinese-red);
        transform: rotate(30deg);
      }
      .modal {
        backdrop-filter: blur(8px);
      }
      .modal-content {
        border-radius: 18px;
        border: none;
      }
      .modal-header {
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      }
      .modal-footer {
        border-top: 1px solid rgba(0, 0, 0, 0.1);
      }
      .input-card {
        background: rgba(255, 255, 255, 0.95);
        border-radius: 18px;
        border: none;
        backdrop-filter: blur(20px);
        transition: all 0.3s ease;
      }
      .input-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      }
      .form-control {
        border-radius: 12px;
        border: 1.5px solid #e5e5e5;
        padding: 0.75rem 1rem;
        font-size: 1rem;
        transition: all 0.3s ease;
      }
      .form-control:focus {
        border-color: var(--chinese-red);
        box-shadow: 0 0 0 0.25rem rgba(200, 16, 46, 0.25);
      }
      .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
      }
      .btn-generate {
        background: var(--chinese-red);
        border: none;
        border-radius: 12px;
        padding: 0.75rem 2rem;
        font-weight: 500;
        transition: all 0.3s ease;
      }
      .btn-generate:hover {
        background: var(--chinese-red-light);
        transform: translateY(-2px);
      }
      .name-card {
        background: white;
        border-radius: 16px;
        border: none;
        transition: all 0.3s ease;
        overflow: hidden;
      }
      .name-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      }
      .name-card .card-body {
        padding: 1.5rem;
      }
      .name-card .chinese-name {
        font-size: 2rem;
        font-weight: 600;
        color: var(--chinese-red);
        margin-bottom: 1rem;
      }
      .name-card .meaning {
        color: #1d1d1f;
        margin-bottom: 0.5rem;
        font-size: 1rem;
      }
      .name-card .translation {
        color: #86868b;
        font-size: 0.9rem;
      }
      .form-check-input:checked {
        background-color: var(--chinese-red);
        border-color: var(--chinese-red);
      }
    </style>
  </head>
  <body>
    <div class="container py-5">
      <button class="settings-btn" id="settingsBtn" title="Settings">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
      </button>
      <div class="row justify-content-center">
        <div class="col-md-10 text-center">
          <h1 class="main-title">Chinese Name Generator</h1>
          <p class="subtitle">Discover your perfect Chinese name with cultural significance</p>
          <div class="card input-card shadow-sm mb-5">
            <div class="card-body p-4">
              <div class="row align-items-end">
                <div class="col-md-4 mb-3 mb-md-0">
                  <label for="lastName" class="form-label">Last Name <small class="text-muted">(姓)</small></label>
                  <input type="text" class="form-control" id="lastName" placeholder="Enter your last name" />
                </div>
                <div class="col-md-4 mb-3 mb-md-0">
                  <label class="form-label">Gender <small class="text-muted">(性别)</small></label>
                  <div class="d-flex gap-4">
                    <div class="form-check">
                      <input class="form-check-input" type="radio" name="gender" id="male" value="male" checked />
                      <label class="form-check-label" for="male">Male <small class="text-muted">(男)</small></label>
                    </div>
                    <div class="form-check">
                      <input class="form-check-input" type="radio" name="gender" id="female" value="female" />
                      <label class="form-check-label" for="female">Female <small class="text-muted">(女)</small></label>
                    </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <button id="generateBtn" class="btn btn-generate btn-primary w-100">
                    Generate Names <small class="d-block text-white-50">生成名字</small>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div id="namesContainer" class="row g-4">
            <!-- Generated names will be displayed here -->
          </div>
        </div>
      </div>
    </div>

    <!-- Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" aria-labelledby="settingsModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="settingsModalLabel">Settings</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label for="apiKey" class="form-label">API Key</label>
              <input type="password" class="form-control" id="apiKey" placeholder="Enter your DeepSeek API key">
              <div class="form-text">Your API key will be saved locally and never shared with anyone.</div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary btn-generate" id="saveSettings">Save</button>
          </div>
        </div>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
      // Initialize settings modal
      const settingsModal = new bootstrap.Modal(document.getElementById('settingsModal'));
      const settingsBtn = document.getElementById('settingsBtn');
      const saveSettingsBtn = document.getElementById('saveSettings');
      const apiKeyInput = document.getElementById('apiKey');

      // Load saved API key
      const savedApiKey = localStorage.getItem('apiKey');
      if (savedApiKey) {
        apiKeyInput.value = savedApiKey;
      }

      // Open settings modal
      settingsBtn.addEventListener('click', () => {
        settingsModal.show();
      });

      // Save settings
      saveSettingsBtn.addEventListener('click', () => {
        const apiKey = apiKeyInput.value.trim();
        if (apiKey) {
          localStorage.setItem('apiKey', apiKey);
          settingsModal.hide();
        } else {
          alert('Please enter a valid API key');
        }
      });

      document.getElementById("generateBtn").addEventListener("click", function () {
        const apiKey = localStorage.getItem('apiKey');
        if (!apiKey) {
          alert('Please set your API key in settings first');
          settingsModal.show();
          return;
        }

        const lastName = document.getElementById("lastName").value.trim();
        const gender = document.querySelector('input[name="gender"]:checked').value;

        if (!lastName) {
          alert("Please enter your last name");
          return;
        }

        const namesContainer = document.getElementById("namesContainer");
        namesContainer.innerHTML = `
          <div class="col-12 text-center">
            <div class="spinner-border text-danger" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
          </div>
        `;

        try {
          fetch("https://api.deepseek.com/chat/completions", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              Accept: "application/json",
              Authorization: `Bearer ${apiKey}`,
            },
            body: JSON.stringify({
              messages: [
                {
                  role: "system",
                  content: `你是一个专业的起名中文专家，请根据用户提供的姓氏和性别，生成3个合适的名字，每个名字都需要符合以下特点
                  1. 名字长度最多不超过4个字符。
                  2. 符合中国传统文化，
                  3. 寓意吉祥，音韵优美，
                  请确保返回的是一个有效的JSON字符串，包含一个对象数组，每个对象包含以下字段：{name:完整的中文名字,chnmean:中文寓意,engmean:英文寓意。`,
                },
                {
                  role: "user",
                  content: `名称：${lastName}，性别：${gender === "male" ? "男" : "女"}孩`,
                },
              ],
              model: "deepseek-chat",
              temperature: 0.7,
              max_tokens: 2048,
            }),
          })
            .then((response) => {
              if (!response.ok) {
                throw new Error("API request failed");
              }
              return response.json();
            })
            .then((data) => {
              console.log("API Response:", data);
              
              const aiResponse = data.choices[0].message.content;
              const names = parseAIResponse(aiResponse);

              namesContainer.innerHTML = "";
              names.forEach((nameInfo) => {
                const nameCard = createNameCard(nameInfo);
                namesContainer.appendChild(nameCard);
              });
            });
        } catch (error) {
          console.error("Error:", error);
          namesContainer.innerHTML = `
            <div class="col-12">
              <div class="alert alert-danger" role="alert">
                Error generating names: ${error.message}
              </div>
            </div>
          `;
        }
      });

      function parseAIResponse(response) {
        try {
          const jsonMatch = response.match(/\[\s*\{.*\}\s*\]/s);
          if (jsonMatch) {
            return JSON.parse(jsonMatch[0]);
          }
          throw new Error("No valid JSON data found");
        } catch (error) {
          console.error("Failed to parse AI response:", error);
          return [];
        }
      }

      function createNameCard(nameData) {
        const col = document.createElement("div");
        col.className = "col-md-4";

        col.innerHTML = `
          <div class="card name-card h-100">
            <div class="card-body">
              <h3 class="chinese-name text-center">${nameData.name}</h3>
              <p class="meaning text-center mb-2">${nameData.chnmean}</p>
              <p class="translation text-center mb-0">${nameData.engmean}</p>
            </div>
          </div>
        `;

        return col;
      }
    </script>
  </body>
</html>
